<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 内容卡片区 -->
        <el-card>
            <!-- 提示 -->
            <el-row>
                <el-alert title="注意：只允许为第三级分类设置相关参数！" show-icon type="warning" :closable="false">
                </el-alert>
            </el-row>
            <!-- 选择商品分类区 -->
            <el-row class="cat-opt">
                <span>选择商品分类：</span>
                <el-cascader v-model="selectCate" :options="cateList" clearable :props="cascaderProps"
                    @change="cateChanged">
                </el-cascader>
            </el-row>
            <!-- 参数设置区 -->
            <el-row>
                <el-tabs v-model="activeName" @tab-click="handleTabClick">
                    <el-tab-pane label="动态参数" name="many">
                        <el-button type="primary" size="mini" :disabled="isBtnDisable"
                            @click="addDialogVisible=true">添加参数</el-button>
                        <!-- 动态参数表格 -->
                        <el-table :data="manyTableData" border stripe>
                            <!-- 展开列 -->
                            <el-table-column type="expand">
                                <template slot-scope="scope">
                                    <el-tag v-for="(tag, index) in scope.row.attr_vals" :key="tag" closable size="small"
                                        @close="handleCloseTag(scope.row, index)">
                                        {{ tag }}
                                    </el-tag>
                                    <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                                    </el-input>
                                    <el-button v-else class="button-new-tag" size="small"
                                        @click="showInput(scope.row)">+ New
                                        Tag</el-button>
                                </template>
                            </el-table-column>
                            <el-table-column type="index" label="#"></el-table-column>
                            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                            <el-table-column label="操作">
                                <template slot-scope="scope">
                                    <el-button type="primary" size="mini" icon="el-icon-edit"
                                        @click="showEditDialog(scope.row.attr_id)">修改</el-button>
                                    <el-button type="danger" size="mini" icon="el-icon-delete"
                                        @click="deleteParam(scope.row.attr_id)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-tab-pane>
                    <el-tab-pane label="静态属性" name="only">
                        <el-button type="primary" size="mini" :disabled="isBtnDisable"
                            @click="addDialogVisible=true">添加属性</el-button>
                        <!-- 静态属性表格 -->
                        <el-table :data="onlyTableData" border stripe>
                            <!-- 展开列 -->
                                                        <!-- 展开列 -->
                            <el-table-column type="expand">
                                <template slot-scope="scope">
                                    <el-tag v-for="(tag, index) in scope.row.attr_vals" :key="tag" closable size="small"
                                        @close="handleCloseTag(scope.row, index)">
                                        {{ tag }}
                                    </el-tag>
                                    <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                                    </el-input>
                                    <el-button v-else class="button-new-tag" size="small"
                                        @click="showInput(scope.row)">+ New
                                        Tag</el-button>
                                </template>
                            </el-table-column>
                            <el-table-column type="index" label="#"></el-table-column>
                            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                            <el-table-column label="操作">
                                <template slot-scope="scope">
                                    <el-button type="primary" size="mini" icon="el-icon-edit"
                                        @click="showEditDialog(scope.row.attr_id)">修改</el-button>
                                    <el-button type="danger" size="mini" icon="el-icon-delete"
                                        @click="deleteParam(scope.row.attr_id)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-tab-pane>
                </el-tabs>
            </el-row>
        </el-card>
        <!-- 添加参数对话框 -->
        <el-dialog :title="'添加'+titleText" :visible.sync="addDialogVisible" width="50%"
            @close="resetForm('addFormRef')">
            <el-form :model="addForm" :rules="formRules" ref="addFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitAddForm">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 编辑参数对话框 -->
        <el-dialog :title="'修改'+titleText" :visible.sync="editDialogVisible" width="50%"
            @close="resetForm('editFormRef')">
            <el-form :model="editForm" :rules="formRules" ref="editFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitEditForm">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            selectCate: [],
            cateList: [],
            cascaderProps: {
                expandTrigger: 'hover',
                value: 'cat_id',
                label: 'cat_name',
                children: 'children'
            },
            // 默认激活标签名称
            activeName: 'many',
            manyTableData: [],
            onlyTableData: [],
            addDialogVisible: false,
            editDialogVisible: false,
            addForm: {
                attr_name: ''
            },
            editForm: {
                attr_name: ''
            },
            formRules: {
                attr_name: [
                    { required: true, message: '请输入参数名称', trigger: 'blur' }
                ]
            },
        }
    },
    created() {
        this.getCateList()
    },
    computed: {
        isBtnDisable() {
            return this.selectCate.length !== 3
        },
        // 当前选中的分类id
        cate_id() {
            if (this.selectCate.length === 3) {
                return this.selectCate[2]
            }
            return null
        },
        titleText() {
            return this.activeName === 'many' ? '动态参数' : '静态属性'
        }
    },
    methods: {
        getCateList() {
            this.$http({
                url: 'categories',
                method: 'get',
            }).then((res) => {
                this.cateList = res.data
            })
        },
        cateChanged() {
            if (this.selectCate.length !== 3) {
                this.selectCate = []
            }
            // 发起请求，获取参数列表
            this.getParams()
        },
        // 切换标签
        handleTabClick() {
            this.getParams()
        },
        getParams() {
            if ( this.selectCate.length !== 3) {
                this.manyTableData = []
                this.onlyTableData = []
                return
            }
            this.$http({
                url: `categories/${this.cate_id}/attributes`,
                method: 'get',
                params: { sel: this.activeName }
            }).then(res => {
                if (res.meta.status === 200) {
                    console.log(res);
                    res.data.forEach(item => {
                        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
                        // 控制文本的显示与隐藏
                        item.inputVisible = false
                        // 文本框输入值
                        item.inputValue = ''
                    });
                    if (this.activeName === 'many') {
                        this.manyTableData = res.data
                    } else {
                        this.onlyTableData = res.data
                    }
                } else {
                    this.$message.error(res.meta.msg)
                }
            }).catch(error => {
                console.log(error);
            })
        },
        resetForm(formName) {
            this.$refs[formName].resetFields()
        },
        submitAddForm() {
            this.$refs.addFormRef.validate(valid => {
                if (valid) {
                    this.$http({
                        url: `categories/${this.cate_id}/attributes`,
                        method: 'post',
                        data: {
                            attr_name: this.addForm.attr_name,
                            attr_sel: this.activeName
                        }
                    }).then(res => {
                        console.log(res);
                        if (res.meta.status === 201) {
                            this.$message.success(res.meta.msg)
                            this.getParams()
                            this.addDialogVisible = false
                        } else {
                            this.$message.error(res.meta.msg)
                        }
                    })
                }
            })
        },
        showEditDialog(attr_id) {
            this.editDialogVisible = true
            this.$http({
                url: `categories/${this.cate_id}/attributes/${attr_id}`,
                method: 'get',
                params: { attr_sel: this.activeName }
            }).then(res => {
                if (res.meta.status === 200) {
                    this.editForm.attr_name = res.data.attr_name
                    this.editForm.attr_id = attr_id
                }
            })
        },
        submitEditForm() {
            this.$refs.editFormRef.validate(valid => {
                if (valid) {
                    this.$http({
                        url: `categories/${this.cate_id}/attributes/${this.editForm.attr_id}`,
                        method: 'put',
                        data: {
                            attr_name: this.editForm.attr_name,
                            attr_sel: this.activeName
                        }
                    }).then(res => {
                        if (res.meta.status === 200) {
                            this.$message.success(res.meta.msg)
                            this.getParams()
                            this.editDialogVisible = false
                        } else {
                            this.$message.error(res.meta.msg)
                        }
                    })
                }
            })
        },
        deleteParam(attr_id) {
            this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$http({
                    url: `categories/${this.cate_id}/attributes/${attr_id}`,
                    method: 'delete',
                }).then(res => {
                    if (res.meta.status === 200) {
                        this.$message.success(res.meta.msg)
                        this.getParams()
                        this.editDialogVisible = false
                    } else {
                        this.$message.error(res.meta.msg)
                    }
                })

            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        submitEditParams(row) {
            this.$http({
                url: `categories/${this.cate_id}/attributes/${row.attr_id}`,
                method: 'put',
                data: {
                    attr_name: row.attr_name,
                    attr_sel: row.attr_sel,
                    attr_vals: row.attr_vals.join(' ')
                }
            }).then(res => {
                if (res.meta.status === 200) {
                    this.$message.success(res.meta.msg)
                    // this.getParams()
                } else {
                    this.$message.error(res.meta.msg)
                }
            })
        },
        handleInputConfirm(row) {
            let inputValue = row.inputValue.trim()
            if (inputValue) {
                row.attr_vals.push(inputValue)
            }
            row.inputValue = ''
            row.inputVisible = false
            this.submitEditParams(row)
        },
        showInput(row) {
            row.inputVisible = true
            // 获取焦点
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus()
            })
        },
        handleCloseTag(row, index) {
            row.attr_vals.splice(index, 1);
            this.submitEditParams(row)

        },
    }

}

</script>

<style scoped>
.cat-opt {
    margin: 15px 0;
}

.el-tag + .el-tag {
    margin-left: 10px;
}
.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}
.input-new-tag {
    width: 90px;
    margin-left: 10px;
}
</style>